//
//  TextView.swift
//  Chatup
//
//  Created by iron man on 2024/1/15.
//

import SwiftUI

struct TextView: View {
    @State var hint: String
    @Binding var text: String
    @FocusState var isFocused: Bool
    var body: some View {
        GeometryReader { proxy in
            ZStack(alignment: .topLeading) {
                RoundedRectangle(cornerRadius: 10)
                    .fill(Color(red: 0.13, green: 0.13, blue: 0.14))
                TextEditor(text: $text)
                    .scrollContentBackground(.hidden)
                    .foregroundColor(.white)
                    .frame(width: proxy.size.width - 40, height: 166)
                    .focused($isFocused)
                    .padding(.horizontal, 20)
                    .onChange(of: text) { newValue in
                        if newValue.count > 200 {
                            text = String(newValue.prefix(200))
                        }
                    }.onReceive(NotificationCenter.default.publisher(for: Notification.Name("kChangeFocused"))) { _ in
                        DispatchQueue.main.async {
                            isFocused = false
                        }
                    }
                if text.isEmpty {
                    Text(hint)
                        .font(.system(size: 18))
                        .foregroundColor(Color(red: 0.61, green: 0.61, blue: 0.61))
                        .frame(alignment: .topLeading)
                        .padding(.horizontal, 22)
                        .padding(.top, 8)
                }
                Spacer()
                HStack {
                    Spacer()
                    Text("\(text.count)/200")
                        .font(Font.custom("SF Pro Display", size: 12))
                        .foregroundColor(Color(red: 0.53, green: 0.53, blue: 0.53))
                        .frame(width: 38, height: 14, alignment: .topLeading)
                        .padding(.horizontal, 8)
                        .padding(.bottom, 8)
                }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
            }
            .frame(width: proxy.size.width, height: 166)
            .onTapGesture {
                isFocused = true
            }
        }
    }
}
